package com.lyy.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.*;
import java.util.Map.Entry;

@Slf4j
public class HttpUtils {

    /**
     * HttpClient GET 提交 Map<String,String>类型数据
     *
     * @param url      主机地址请求路径
     * @param paramMap 参数Map
     * @return
     */
    public static String sendGet(String url, Map<String, String> paramMap) throws Exception {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet();
        String body = "";
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        Set<Entry<String, String>> set = paramMap.entrySet();
        for (Entry<String, String> entry : set) {
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        String param = URLEncodedUtils.format(formparams, "UTF-8");
        httpGet.setURI(URI.create(url + "?" + param));
        HttpResponse response = httpClient.execute(httpGet);
        body = EntityUtils.toString(response.getEntity(), "utf-8");
        return body;
    }

    /**
     * HttpClient GET 提交 Map<String,String>类型数据
     *
     * @param url      主机地址请求路径
     * @param paramMap 参数Map
     * @return
     */
    public static String sendGet(String url, Map<String, String> paramMap, Map<String, String> header) throws Exception {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet();
        // 设置请求的header
        if (null != header) {
            Set<String> set = header.keySet();
            for (Iterator<String> iter = set.iterator(); iter.hasNext(); ) {
                String key = (String) iter.next();
                String value = (String) header.get(key);
                httpGet.setHeader(key, value);
            }
        }
        String body = "";
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        Set<Entry<String, String>> set = paramMap.entrySet();
        for (Entry<String, String> entry : set) {
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        String param = URLEncodedUtils.format(formparams, "UTF-8");
        httpGet.setURI(URI.create(url + "?" + param));
        HttpResponse response = httpClient.execute(httpGet);
        body = EntityUtils.toString(response.getEntity(), "utf-8");
        return body;
    }

    /**
     * HttpClient DELETE 提交 Map<String,String>类型数据
     *
     * @param url      主机地址请求路径
     * @param paramMap 参数Map
     * @return
     */
    public static String sendDelete(String url, Map<String, String> paramMap) throws IOException {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpDelete httpDelete = new HttpDelete();
        String body = "";
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        Set<Entry<String, String>> set = paramMap.entrySet();
        for (Entry<String, String> entry : set) {
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        String param = URLEncodedUtils.format(formparams, "UTF-8");
        httpDelete.setURI(URI.create(url + "?" + param));
        HttpResponse response = httpClient.execute(httpDelete);
        body = EntityUtils.toString(response.getEntity(), "utf-8");
        return body;
    }

    /**
     * HttpClient DELETE 提交 Map<String,String>类型数据
     *
     * @param url      主机地址请求路径
     * @param paramMap 参数Map
     * @return
     */
    public static String sendDelete(String url, Map<String, String> paramMap, Map<String, String> header) throws IOException {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpDelete httpDelete = new HttpDelete();
        String body = "";
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        Set<Entry<String, String>> set = paramMap.entrySet();
        for (Entry<String, String> entry : set) {
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        String param = URLEncodedUtils.format(formparams, "UTF-8");
        httpDelete.setURI(URI.create(url + "?" + param));
        if (null != header) {
            Set<String> s = header.keySet();
            for (Iterator<String> iter = s.iterator(); iter.hasNext(); ) {
                String key = (String) iter.next();
                String value = (String) header.get(key);
                httpDelete.setHeader(key, value);
            }
        }
        HttpResponse response = httpClient.execute(httpDelete);
        body = EntityUtils.toString(response.getEntity(), "utf-8");
        return body;
    }

    /**
     * HttpClient PUT 提交 Map<String,String>类型数据
     *
     * @param url      主机地址请求路径
     * @param paramMap 参数Map
     * @return
     */
    public static String sendPUT(String url, Map<String, String> paramMap) throws IOException {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut();
        String body = "";
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        Set<Entry<String, String>> set = paramMap.entrySet();
        for (Entry<String, String> entry : set) {
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        String param = URLEncodedUtils.format(formparams, "UTF-8");
        httpPut.setURI(URI.create(url + "?" + param));
        HttpResponse response = httpClient.execute(httpPut);
        body = EntityUtils.toString(response.getEntity(), "utf-8");
        return body;
    }

    /**
     * HttpClient POST 提交 Map<String,String>类型数据
     *
     * @param url      主机地址请求路径
     * @param paramMap 参数Map
     * @return
     */
    public static String sendPost(String url, Map<String, String> paramMap) {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);
        String body = "";
        if (httpPost != null && paramMap != null) {
            try {
                // 装填参数
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                for (Entry<String, String> entry : paramMap.entrySet()) {
                    nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                // 设置参数到请求对象中
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
                // 设置header信息
                // 指定报文头【Content-type】
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
                // 执行请求操作，并拿到结果（同步阻塞）
                CloseableHttpResponse response = httpClient.execute(httpPost);
                // 获取结果实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    // 按指定编码转换结果实体为String类型
                    body = EntityUtils.toString(entity, "utf-8");
                }
                EntityUtils.consume(entity);
                // 释放链接
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
        return body;
    }

    /**
     * HttpClient POST 提交 Map<String,String>类型数据
     *
     * @param url         主机地址请求路径
     * @param json        参数Json
     * @param Map<String, String> map header参数
     * @return
     */
    public static String sendBtgJsonPost(String url, String json, Map<String, String> map) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        String body = null;
        try {
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            // 设置请求的header
            if (null != map) {
                Set<String> set = map.keySet();
                for (Iterator<String> iter = set.iterator(); iter.hasNext(); ) {
                    String key = (String) iter.next();
                    String value = (String) map.get(key);
                    httpPost.setHeader(key, value);
                }
            }
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();//设置请求和传输超时时间
            httpPost.setConfig(requestConfig);
            httpPost.setEntity(new StringEntity(json, "utf-8"));
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                body = EntityUtils.toString(response.getEntity());
                log.info("返回信息::" + body);
            } catch (Exception e) {
                log.error("获取返回信息失败::::" + e);
            } finally {
                response.close();
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        return body;
    }

    /**
     * HttpClient POST 提交 Map<String,String>类型数据
     *
     * @param url  主机地址请求路径
     * @param json 参数Json
     * @return
     */
    public static String sendJsonPost(String url, String json, Map<String, String> map) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        String body = null;
        try {
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            // 设置请求的header
            if (null != map) {
                Set<String> set = map.keySet();
                for (Iterator<String> iter = set.iterator(); iter.hasNext(); ) {
                    String key = (String) iter.next();
                    String value = (String) map.get(key);
                    httpPost.setHeader(key, value);
                }
            }
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();//设置请求和传输超时时间
            httpPost.setConfig(requestConfig);
            httpPost.setEntity(new StringEntity(json, "utf-8"));
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                body = EntityUtils.toString(response.getEntity());
                log.info("返回信息::" + body);
            } catch (Exception e) {
                log.error("获取返回信息失败::::" + e);
            } finally {
                response.close();
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        return body;
    }

    /**
     * HttpClient PUT 提交 Map<String,String>类型数据
     *
     * @param url  主机地址请求路径
     * @param json 参数Json
     * @return
     */
    public static String sendJsonPut(String url, String json, Map<String, String> map) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        String body = null;
        try {
            httpPut.addHeader("Content-type", "application/json; charset=utf-8");
            httpPut.setHeader("Accept", "application/json");
            // 设置请求的header
            if (null != map) {
                Set<String> set = map.keySet();
                for (Iterator<String> iter = set.iterator(); iter.hasNext(); ) {
                    String key = (String) iter.next();
                    String value = (String) map.get(key);
                    httpPut.setHeader(key, value);
                }
            }
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();//设置请求和传输超时时间
            httpPut.setConfig(requestConfig);
            httpPut.setEntity(new StringEntity(json, "utf-8"));
            CloseableHttpResponse response = httpClient.execute(httpPut);
            try {
                body = EntityUtils.toString(response.getEntity());
                log.info("返回信息::" + body);
            } catch (Exception e) {
                log.error("获取返回信息失败::::" + e);
            } finally {
                response.close();
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        return body;
    }

    /**
     * HttpClient GET 提交Json类型数据
     *
     * @param url  主机地址请求路径
     * @param json 参数json
     * @param map  HTTP Headers
     * @return
     */
    public static String createGetClient(String url, String json, Map<String, String> map) throws Exception {
        String returnStr = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        // 设置请求的header
        if (null != map) {
            Set<String> set = map.keySet();
            for (Iterator<String> iter = set.iterator(); iter.hasNext(); ) {
                String key = (String) iter.next();
                String value = (String) map.get(key);
                httpGet.setHeader(key, value);
            }
        }
        // 执行请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        returnStr = EntityUtils.toString(response.getEntity(), "utf-8");
        // 执行请求
        return returnStr;
    }

    /**
     * HttpClient POST 提交Json类型数据
     *
     * @param url  主机地址请求路径
     * @param json 参数json
     * @param map  HTTP Headers
     * @return
     */
    public static String createPostClient(String url, String json, Map<String, String> map) throws Exception {
        String returnStr = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        // 设置请求的header
        if (null != map) {
            Set<String> set = map.keySet();
            for (Iterator<String> iter = set.iterator(); iter.hasNext(); ) {
                String key = (String) iter.next();
                String value = (String) map.get(key);
                httpPost.setHeader(key, value);
            }
        }
        // 设置请求的参数
        StringEntity se = new StringEntity(json, "UTF-8");
        se.setContentType("text/javascript");
        httpPost.setEntity(se);
        // 执行请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        returnStr = EntityUtils.toString(response.getEntity(), "utf-8");
        return returnStr;
    }

    /**
     * HttpClient POST 提交Json类型数据
     *
     * @param url  主机地址请求路径
     * @param json 参数json
     * @param map  HTTP Headers
     * @return
     */
    public static String createPutClient(String url, String json, Map<String, String> map) throws Exception {
        String returnStr = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        // 设置请求的header
        if (null != map) {
            Set<String> set = map.keySet();
            for (Iterator<String> iter = set.iterator(); iter.hasNext(); ) {
                String key = (String) iter.next();
                String value = (String) map.get(key);
                httpPut.setHeader(key, value);
            }
        }
        // 设置请求的参数
        StringEntity se = new StringEntity(json, "UTF-8");
        se.setContentType("text/javascript");
        httpPut.setEntity(se);
        // 执行请求
        CloseableHttpResponse response = httpClient.execute(httpPut);
        returnStr = EntityUtils.toString(response.getEntity(), "utf-8");
        return returnStr;
    }

}